import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'
// const Login = () =>  import('@/views/login')

// 右箭头 左箭头：  移动移动一个格子
// ctrl + 右箭头： 移动到一个单词前后
// fn + 左/右箭头: fn+左箭头=home  fn+右箭头=end  移动到最前面和最后面
// 退格键 ===删除键
const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const Articles = () => import('@/views/layout/articles')
const AddArticle = () => import('@/views/layout/articles/add')
const EditArticle = () => import('@/views/layout/articles/edit')
const Home = () => import('@/views/layout/home')
const Pictures = () => import('@/views/layout/pictures')
const Comments = () => import('@/views/layout/comments')
const Fans = () => import('@/views/layout/Fans')
const Setting = () => import('@/views/layout/setting')
const PageNotFound = () => import('@/views/404')

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/', component: Home },
      { path: '/articles', component: Articles },
      { path: '/pictures', component: Pictures },
      { path: '/add-article', component: AddArticle },
      { path: '/comments', component: Comments },
      { path: '/fans', component: Fans },
      { path: '/edit-article/:id', component: EditArticle },
      { path: '/setting', component: Setting }
      // shift + alt + 下箭头
      // alt + 下箭头
    ]
  },
  {
    // 匹配所有的路径 兜底方案
    path: '*',
    component: PageNotFound
  }
]

const router = new VueRouter({
  routes
})

// 配置了路由的全局前置导航守卫
/*
  1. 判断去的页面是否是登录，如果是登录，让走
  2. 如果不是登录页面。判断是否有token
  3. 如果有token，让走
  4. 如果没有token, 拦截到登录去

  1. 判断有无token
  2. 如果有token,放行
  3. 如果没有token
  4. 判断是否是去login,如果是，放行
  5. 如果不是，去登录
*/
router.beforeEach((to, from, next) => {
  // console.log('to', to)
  // console.log('from', from)
  // next是一个函数，代表放行
  // next('/login')
  // next()
  const token = getToken()
  if (token || to.path === '/login') {
    next()
  } else {
    next('/login')
  }
})

export default router
